package com.szj.spushrtmp.util.audio;

import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;

import com.szj.spushrtmp.util.SLog;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @ClassName: AudioRecorderManager
 * @Author: s10g
 * @CreateDate: 8/3/23$ 10:13 AM$
 * TODO
 */
public class AudioRecorderManager {
    AudioRecord audioRecord;
    private final ExecutorService executorService; // 线程池 就是为了执行子线程而已

    public AudioReadListener audioReadListener;

    public final AudioRecorderRunnable runnable;
    int inputSamples = 4096; // 4096


    public boolean isPlay;

    /*
     * 作者:s10g
     * 创建时间: 8/3/23 10:14 AM
     * TODO
     * channel 通道数
     * hz: 采样率
     * hz: 输入样本数
     */
    public AudioRecorderManager(int channel, int hz, int inputSample) {
        executorService = Executors.newSingleThreadExecutor(); // 单例线程池而已，就相当于 new Thread
        runnable = new AudioRecorderRunnable();

        // 获取最小缓存长度
        int minBufferSize = AudioRecord.getMinBufferSize(hz, channel, AudioFormat.ENCODING_PCM_16BIT) * channel;

        SLog.i("AudioRecorderManager : minBufferSize:" + minBufferSize + "\tinputSample:" + inputSample);
        audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, // 安卓手机的麦克风
                hz,  // 采样率
                channel, // 声道数 双声道
                AudioFormat.ENCODING_PCM_16BIT, // 采样位深度 16位 2字节
                Math.max(minBufferSize, inputSample)); // 缓冲区大小（以字节为单位）：max在两者中取最大的，内置缓冲 buff size 大一些 没关系的，能大 但是不能小

        /*
             每秒消耗流量 = 采样率 * 采样位深度 * 通道数
             = 44100Hz * 2byte(8bit) * 2
             = 176400bit/s
             约等于 172KB/s
         */
    }

    public void start() {
        isPlay = true;
        audioRecord.startRecording();

        executorService.submit(runnable);
    }

    public void stop() {
        isPlay = false;
        audioRecord.stop();
    }

    public void release() {
        audioRecord.release();
        audioRecord = null;
    }

    public class AudioRecorderRunnable implements Runnable {
        @Override
        public void run() {
            byte[] data = new byte[inputSamples];
            while (isPlay) {
                int len = audioRecord.read(data, 0, data.length);
                if (len > 0) {
//                    SLog.i("runnable:len:" + len + "\tdata.length:" + data.length);

                    if (audioReadListener != null)
                        audioReadListener.result(data, len);
                }
            }

            isPlay = false;
            audioRecord.stop();
        }
    }

    public void setAudioReadListener(AudioReadListener readListener) {
        audioReadListener = readListener;
    }
}
